<?php 
class image{
	public function resize($path_img,$width,$height,$path_img_dest,$ratio=null){
		if($path_img && $path_img_dest){
			$img_type = $this->type($path_img);
			if($img_type==IMG_GIF){
				$img = imagecreatefromgif($path_img);
			}elseif($img_type==IMG_PNG){
				$img = imagecreatefrompng($path_img);
			}elseif($img_type==IMG_JPG){
				$img = imagecreatefromjpeg($path_img);
			}
			$size = getimagesize($path_img);
			if($ratio=="w" && $width){
				if($width>$size[0]){//只有当目标图片小于原始图片时才需要裁剪
					return copy($path_img,$path_img_dest);
				}
				$height = (int)(($width*$size[1])/$size[0]);
			}else if($ratio="h" && $height){
				if($height>$size[1]){//只有当目标图片小于原始图片时才需要裁剪
					return copy($path_img,$path_img_dest);
				}
				$width = (int)(($height*$size[0])/$size[1]);
			}else if(!$width || !$height){
				return false;
			}
			if(function_exists("imagecreatetruecolor")){
				$img2 = imagecreatetruecolor($width,$height);
			}else{
				$img2 = imagecreate($width,$height);
			}
			if(function_exists("imagecopyresampled")){
				$res = imagecopyresampled($img2,$img,0,0,0,0,$width,$height,$size[0],$size[1]);
			}else{
				$res = imagecopyresized($img2,$img,0,0,0,0,$width,$height,$size[0],$size[1]);
			}
			if($res){
				return imagejpeg($img2,$path_img_dest,100);
			}
			return false;
		}else{
			return false;
		}
	}
	public function content_type($path_img){
		switch (exif_imagetype($path_img)) {
		    case IMAGETYPE_GIF:
		        $image_type = "image/gif";
		        break;
		    case IMAGETYPE_JPEG:
		        $image_type = "image/jpeg";
		        break;
		    case IMAGETYPE_PNG:
		        $image_type = "image/png";
		        break;
		    case IMAGETYPE_WBMP:
		        $image_type = "image/x-ms-bmp";
		        break;
			default:
		        $image_type = null;
		        break;
		}
		return $image_type;
	}
	public function type_to_content_type($imagetype){
		$content_type = "";
		switch($imagetype){
			case IMG_GIF:
				$content_type = "image/gif";
				break;
			case IMG_JPG:
				$content_type = "image/jpeg";
				break;
			case IMG_PNG:
				$content_type = "image/png";
				break;
			case IMG_WBMP:
				$content_type = "image/x-ms-bmp";
				break;
			default:
				$content_type = "";
		}
		return $content_type;
	}
	public function type($path_img){
		$image_type = 0;
		switch (exif_imagetype($path_img)) {
		    case IMAGETYPE_GIF:
		        $image_type = IMG_GIF;
		        break;
		    case IMAGETYPE_JPEG:
		        $image_type = IMG_JPG;
		        break;
		    case IMAGETYPE_JPEG2000:
		        $image_type = IMG_JPG;
		        break;
		    case IMAGETYPE_PNG:
		        $image_type = IMG_PNG;
		        break;
		    case IMAGETYPE_WBMP:
		        $image_type = IMG_WBMP;
		        break;
			default:
		        $image_type = 0;
		        break;
		}
		return $image_type;
	}
	
}
?>